<?php

namespace app\back\controller;
use app\back\model\Category;
use \think\Controller;
use app\back\model\Product;
use app\back\validate\ProductValidate;
use think\Db;
use think\Cache;
use think\Image;


class ProductController extends Controller
{
    const CACHE_TYPE_KEY = "cache_key";


    //添加修改商品
    public function setAction()
    {

        $req = request();
        if($req->isGet()){
            $m = session("message");
            $i = session("info");
            $id =input("id");
            $one = Product::get($id);
            if(!(isset($m)&&isset($i))){
                $message = "";
                $info =$one;
            }
            else{
                $message = $m;
                $info =$i;
            }

            $list = [];
            if(!($list=Cache::get(self::CACHE_TYPE_KEY))){
                $list = (new Category())->getTree();
                Cache::set(self::CACHE_TYPE_KEY,$list);
            }
            $this->assign("msg",$message);
            $this->assign("info",$info);
            $this->assign("id",$id);
            $this->assign("unit_list",Db::name("unit")->select());
            $this->assign("brand_list",Db::name("brand")->select());
            $this->assign("category_list",$list);
            return $this->fetch();
        }
        elseif ($req->isPost()){
            $model = new Product;
            $v = new  ProductValidate;
            $data = input("post.");
            if(!$v->batch(true)->check($data)){
                $data["id"] = isset($data["id"]) ? $data["id"] : null;
                return $this->redirect("set",["id" => $data["id"]],202,[
                    "message"=>$v->getError(),
                    "info" => $data
                ]);
            }
            $result = null;
            $data["description"] = htmlspecialchars( $data["description"] );
            if(!empty($data["id"])){
                $one = $model->find($data["id"]);
                $result = $one->save($data);
            }
            else{
                $result = $model->save($data);
            }
            if(!$result){
                return "添加失败：".$this->error();
            }
            else{
                return $this->redirect("index");
            }


        }
        else{


        }

    }


    //筛选
    public function indexAction()
    {
        $filter=input("filter/a");
        $filter_order=[];
        $m = new Product();


        
        //筛选查询字段title

        if(isset($filter["title"])){
        $str = str_replace("%","\%",$filter["title"]);
        $m->where("title","like","%".$str."%");
        $filter_order["filter[title]"] = $filter["title"];
        }

        //筛选查询字段upc

        if(isset($filter["upc"])){
        $str = str_replace("%","\%",$filter["upc"]);
        $m->where("upc","like","%".$str."%");
        $filter_order["filter[upc]"] = $filter["upc"];
        }

        //筛选查询字段price

        if(isset($filter["price"])){
        $str = str_replace("%","\%",$filter["price"]);
        $m->where("price","like","%".$str."%");
        $filter_order["filter[price]"] = $filter["price"];
        }

        //筛选查询字段status

        if(isset($filter["status"])){
        $str = str_replace("%","\%",$filter["status"]);
        $m->where("status","like","%".$str."%");
        $filter_order["filter[status]"] = $filter["status"];
        }


        $order = input("order/a");
        if(isset($order)){
            $m->order([$order["field"] =>$order["type"]]);
        }
        $size =5;
        $list = $m->paginate($size,false,['query' => request()->param()]);
        $start = $size*($list->currentPage()-1)+1;
//        $end =min($list->total(),$list->currentPage()*$size);
        $end = $start+count($list)-1;
        $this->assign("start",$start);
        $this->assign("end",$end);
        $this->assign("list",$list);
        $this->assign("filter",$filter);
        $this->assign("order",$order);
        $this->assign("filter_order",$filter_order);
        return $this->fetch();
    }




    //删除

    public function multiAction()
    {
        $data = input("selected/a");
        if(count($data)==0) $this->redirect("index");

        Product::destroy($data);
        $this->redirect("index");
    }

    //上传图片

    public function uploadAction()
    {
        $file = request()->file("file");
        if($file){
            $result = $file->validate(["size"=>1*1024*1024,"ext"=>"jpg,png,gif"])->move(ROOT_PATH."public/upload/product");
            if($result){
                $img = Image::open(ROOT_PATH."public/upload/product/".$result->getSaveName());
                $thumb_img = ROOT_PATH."public/upload/thumb/product/".dirname($result->getSaveName())."/thumb_".$result->getFilename();
                if(!is_dir(dirname($thumb_img))){
                    mkdir(dirname($thumb_img),0755,true);
                }
                $f = $img->thumb(60,60,Image::THUMB_FILLED)->save($thumb_img);
                return [
                  "image"=>  $result->getSaveName(),
                  "image_thumb" => dirname($result->getSaveName())."/thumb_".$result->getFilename(),
                ];


            }else{
                return [
                    "error"=>$file->getError()
                ];

            }

        }

    }




}





